import axios from '@/config/axios/index.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { VxeUI } from '@/config/vxe/index.ts';
import { reactive, ref } from 'vue';
import { VxeGridInstance, VxeGridProps } from 'vxe-table';
import { FormProps } from 'naive-ui';
import type { DictTypeProps } from '#/src/components/page/systemManager/dictMaintain/DictionaryMaintain.d.ts';
const useLeftGridHooks = (props: any, leftAddModalRef: any, leftEditModalRef: any) => {
	const currentDictType = reactive<Partial<DictTypeProps>>({});
	const leftGridRef = ref<VxeGridInstance>();
	const leftGridConfig = reactive<VxeGridProps>({
		loading        : false,
		stripe         : false,
		height         : 'auto',
		align          : 'center',
		keyboardConfig : { isArrow : true },
		pagerConfig    : {
			currentPage : 1,
			pageSize    : 20,
			total       : 0
		},
		toolbarConfig  : {},
		formConfig     : {
			enabled : false,
			data    : {
				dictTypeCode : null,
				dictTypeName : null
			}
		},
		rowConfig      : {
			keyField : 'id',
			useKey   : true
		},
		columns        : [
			{
				field        : 'sort',
				title        : '序号',
				showOverflow : 'tooltip'
			},
			{
				field        : 'dictTypeName',
				title        : '字典类型名称',
				showOverflow : 'tooltip'
			},
			{
				field        : 'dictTypeCode',
				title        : '字典类型编码',
				showOverflow : 'tooltip'
			},
			{
				field      : 'status',
				title      : '是否启用',
				cellRender : {
					name   : 'n-switch',
					props  : {
						size           : 'large',
						checkedValue   : true,
						uncheckedValue : false,
						slots          : {
							checked   : '启用',
							unchecked : '禁用'
						}
					},
					events : {
						toggleEvent : (row: any) => toggleStatus(row)
					}
				}
			},
			{
				title        : '操作',
				showOverflow : 'tooltip',
				slots        : {
					// 使用 JSX 渲染
					default : 'operate'
				}
			}
		],
		data           : [],
		// @ts-ignore
		onPageChange : (params: any) => changeLeftPage(params),
		onCellClick  : (params: any) => onCellClick(params)
	});
	const leftFormConfig = reactive<FormProps>({
		labelWidth           : 'auto',
		labelAlign           : 'left',
		labelPlacement       : 'left',
		size                 : 'small',
		showFeedback         : false,
		requireMarkPlacement : 'right-hanging'
	});
	const initLeftGrid = async (): Promise<void> => {
		leftGridConfig.loading = true;
		leftGridRef.value?.clearCurrentRow();
		leftGridRef.value?.clearCurrentColumn();
		axios<any, JsonResultProps<any>, any>({
			method : 'POST',
			url    : '/dict/type/pagingList',
			data   : {
				pageNum  : leftGridConfig.pagerConfig!.currentPage,
				pageSize : leftGridConfig.pagerConfig!.pageSize,
				...leftGridConfig.formConfig!.data
			}
		}).then((jsonResult: JsonResultProps<any>) => {
			if (jsonResult.status) {
				leftGridConfig.pagerConfig!.total = jsonResult.data.total;
				leftGridConfig.data = jsonResult.data.records;
			} else {
				VxeUI.modal.message({
					content : jsonResult['msg'],
					status  : 'warning',
					id      : 'failedMessage'
				});
			}
			leftGridConfig.loading = false;
		}).catch((error: unknown) => {
			console.error(error);
			VxeUI.modal.message({
				content : '系统异常,请稍后再试',
				status  : 'error',
				id      : 'errorMessage'
			});
			leftGridConfig.loading = false;
		});
	};
	const changeLeftPage = async ({ currentPage, pageSize }: { currentPage: number, pageSize: number }) => {
		leftGridConfig.pagerConfig!.currentPage = currentPage;
		leftGridConfig.pagerConfig!.pageSize = pageSize;
		await initLeftGrid();
	};
	const queryLeftCondition = async (): Promise<void> => {
		await initLeftGrid();
	};
	const resetLeftQueryCondition = async (): Promise<void> => {
		leftGridConfig.formConfig!.data = {
			dictTypeCode : null,
			dictTypeName : null
		};
		await initLeftGrid();
	};
	const showAddDictTypeModal = async (): Promise<void> => {
		leftAddModalRef.value?.showModal();
	};
	const showEditDictTypeModal = async (event: MouseEvent, rowData: DictTypeProps): Promise<void> => {
		event.preventDefault();
		event.stopPropagation();
		event.stopImmediatePropagation();
		leftEditModalRef.value?.showModal(rowData);
	};
	const removeDictType = async (event: MouseEvent, rowData: DictTypeProps): Promise<void> => {
		event.preventDefault();
		event.stopPropagation();
		event.stopImmediatePropagation();
		VxeUI.modal.confirm({
			content : '关联的字典值也会级联删除,\n您确定要删除该字典分类吗?',
			title   : '你真的确定吗?',
			id      : 'deleteModalUnique'
		}).then((type: any) => {
			if ('confirm' === type) {
				axios<any, JsonResultProps<any>, any>({
					method : 'DELETE',
					url    : `/dict/type/remove/${rowData.dictTypeCode}`
				}).then((jsonResult: any) => {
					if (jsonResult['status']) {
						initLeftGrid();
						VxeUI.modal.message({
							content : jsonResult['msg'],
							status  : 'success',
							id      : 'successMessage'
						});
					} else {
						VxeUI.modal.message({
							content : jsonResult['msg'],
							status  : 'warning',
							id      : 'failedMessage'
						});
					}
				}).catch(errorObj => {
					console.error(errorObj);
					VxeUI.modal.message({
						content : '系统异常,请稍后再试',
						status  : 'error',
						id      : 'errorMessage'
					});
				});
			}
		});
	};
	const onCellClick = async ({ row, $event }: { row: DictTypeProps, $event: MouseEvent }): Promise<void> => {
		Object.assign(currentDictType, row);
	};
	const toggleStatus = async (rowData: DictTypeProps) => {
		console.log(rowData);
		axios<any, JsonResultProps<any>, any>({
			method : 'PATCH',
			url    : `/dict/type/status/${rowData.dictTypeCode}`
		}).then((jsonResult: JsonResultProps<any>) => {
			if (jsonResult['status']) {
				initLeftGrid();
			} else {
				VxeUI.modal.message({
					content : jsonResult['msg'],
					status  : 'warning',
					id      : 'failedMessage'
				});
			}
		}).catch((error: unknown) => {
			console.error(error);
			VxeUI.modal.message({
				content : '系统异常,请稍后再试',
				status  : 'error',
				id      : 'errorMessage'
			});
		});
	};
	return {
		currentDictType,
		leftGridRef, leftGridConfig,
		leftFormConfig,
		initLeftGrid, queryLeftCondition, resetLeftQueryCondition,
		showAddDictTypeModal, showEditDictTypeModal, removeDictType
	};
};
export default useLeftGridHooks;